package com.kuang.lock;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: juc
 * @description:
 * @author: 陈恩涛
 * @create: 2021-03-29 10:29
 **/
public class Demo02 {
    public static void main(String[] args) {
        Phone2 phone = new Phone2();

        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                Runtime.getRuntime().availableProcessors(),
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                namedThreadFactory,
                new ThreadPoolExecutor.AbortPolicy()
        );

        threadPoolExecutor.execute(() -> {
            phone.sendMsg();
        });

        threadPoolExecutor.execute(() -> {
            phone.sendMsg();
        });

    }
}

class Phone2 {

    Lock lock = new ReentrantLock();

    public void sendMsg() {
        lock.lock();
        //细节问题； lock.lock(); lock.unlock(); 锁必须配对，否则就会死在里面
        // lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+" 发短信！");
            call(); // 这里也有锁
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void call() {

        lock.lock();

        try {
            System.out.println(Thread.currentThread().getName()+" 打电话！");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

}
